﻿#region
using System;
using System.Linq;
using System.Reflection;
using System.Windows.Forms;
using System.Xml;
using GFCTP;
using GFTradePlat.Properties;
using WeifenLuo.WinFormsUI.Docking;

#endregion

namespace GFTradePlat
{
	public partial class MainForm : Form
	{
		private readonly FormPropertyEx _fGf = new FormPropertyEx();
		private readonly FormPropertyEx _fWs = new FormPropertyEx();
		private readonly GF _gf = new GF();
		private int _childFormNumber;

		public MainForm()
		{
			this.InitializeComponent();
		}

		private void MainForm_Load(object sender, EventArgs e)
		{
			this._gf.IP = Settings.Default.IP;
			this._gf.Port = Settings.Default.Port;
			this._fGf.CloseButtonVisible = false;
			this._fWs.CloseButtonVisible = false;
			this._fGf.Text = this._fGf.Name = "全局";
			this._fWs.Text = this._fWs.Name = "工作区";
			this._fGf.Show(this.dockPanel1);
			this._fGf.DockTo(this.dockPanel1, DockStyle.Left);
			this._fWs.Show(this.dockPanel1);
			this._fWs.DockTo(this.dockPanel1, DockStyle.Left);
			this._fWs.propertyGridEx1.PropertyValueChanged += (obj, arg) =>
			                                                  {
				                                                  FormWorkSpace f = (FormWorkSpace) ActiveMdiChild;
				                                                  switch (arg.ChangedItem.Label)
				                                                  {
					                                                  case "Name":
						                                                  f.Text = f.TabText = (string) arg.ChangedItem.Value;
						                                                  break;
				                                                  }
			                                                  };
			this._fGf.propertyGridEx1.SelectedObject = this._gf;
		}

		private void MainForm_FormClosed(object sender, FormClosedEventArgs e)
		{
            Properties.Settings.Default.IP = _gf.IP;
            Properties.Settings.Default.Port = _gf.Port;
			Properties.Settings.Default.Save();

			CloseAllToolStripMenuItem_Click(null, null);
			foreach (var v in _gf.Apis)
			{
				v.Release();
			}
			this._gf.MD.Release();
		}

		private void ShowNewForm(object sender, EventArgs e)
		{
			FormWorkSpace childForm = new FormWorkSpace();
			childForm.ws = this._gf.WorkSpaces.Add(); // new WorkSpace(_gf);
			//_gf.WorkSpaces.Add(childForm.ws);
			childForm.Show(this.dockPanel1, DockState.Document);
			//childForm.DockTo(this.dockPanel1, DockStyle.Fill);
			childForm.MdiParent = this;
			childForm.TabText = childForm.Text = childForm.ws.Name = "工作区" + this._childFormNumber++; //此处有联动,待测试
			//childForm.Show();
			//childForm.ws = _gf.WorkSpaces.Add();
			//childForm.ws.Datas.Add(new Data("IF1305", 15, EnumIntervalType.Minute));
			//childForm.ws.ReadData();
			//Sample sample = new Sample();
			//childForm.ws.Strategies.Add(sample);
			//var o = sample.Operations;
			return;
		}

		private void OpenFile(object sender, EventArgs e)
		{
			OpenFileDialog openFileDialog = new OpenFileDialog();
			openFileDialog.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
			openFileDialog.Filter = "文本文件(*.ws)|*.ws|所有文件(*.*)|*.*";
			if (openFileDialog.ShowDialog(this) != DialogResult.OK)
			{
				return;
			}
			string fileName = openFileDialog.FileName;
			//"<Content ID={0} DockState={1} IsFloat={2}\r\n", i++, f.DockState, f.IsFloat)
			XmlDocument doc = new XmlDocument();
			doc.Load(fileName);
			XmlElement root = doc.DocumentElement;
			foreach (XmlNode work in root.ChildNodes)
			{
				FormWorkSpace f = new FormWorkSpace();
				string tmp = string.Empty;
				if (!string.IsNullOrEmpty((tmp = work.Attributes["DockState"].InnerText)))
				{
					f.Show(this.dockPanel1, (DockState) Enum.Parse(typeof (DockState), tmp));
					f.DockTo(this.dockPanel1, DockStyle.Fill);
				}
				f.ws = this._gf.WorkSpaces.Add();
				f.Text = f.ws.Name = work.Attributes["Name"].InnerText;
				f.ws.StartTime = DateTime.Parse(work.Attributes["StartTime"].InnerText);
				f.ws.StopTime = DateTime.Parse(work.Attributes["StopTime"].InnerText);
				f.ws.ReceiveTickEnable = bool.Parse(work.Attributes["ReceiveTickEnable"].InnerText);
				if (f.ws.ReceiveTickEnable)
				{
					f.ws.StopTime = DateTime.Today;
				}
				//Data
				foreach (XmlElement eData in work.SelectSingleNode("Datas").ChildNodes)
				{
					Data data = new Data();
					data.Instrument = eData.Attributes["Instrument"].InnerText;
					data.InstrumentOrder = eData.Attributes["InstrumentOrder"].InnerText;
					data.Interval = int.Parse(eData.Attributes["Interval"].InnerText);
					data.IntervalType = (EnumIntervalType) Enum.Parse(typeof (EnumIntervalType), eData.Attributes["IntervalType"].InnerText);
					f.ws.Datas.ReadData(data);
				}
				//Strategy
				XmlNode selectSingleNode = work.SelectSingleNode("Strategies");
				if (selectSingleNode != null)
				{
					foreach (XmlElement eStrategy in selectSingleNode.ChildNodes)
					{
						Type t = Type.GetType(eStrategy.Attributes["Type"].InnerText);
						if (t == null)
						{
							continue;
						}
						Strategy stra = (Strategy) Activator.CreateInstance(t);
						//Parameters
						XmlElement xmlElement = eStrategy["Params"];
						if (xmlElement != null)
						{
							foreach (XmlElement eParam in xmlElement.ChildNodes)
							{
								stra.SetParameterValue(eParam.Attributes[0].Name, eParam.Attributes[0].Value);
							}
						}
						f.ws.Strategies.LoadStrategy(stra);
					}
				}
				// APIs ==> 每次登录后用户手工登录,建议关联 <==
				ActivateMdiChild(f);
				this.MainForm_MdiChildActivate(null, null);
			}
		}

		private void SaveAsToolStripMenuItem_Click(object sender, EventArgs e)
		{
			SaveFileDialog saveFileDialog = new SaveFileDialog();
			saveFileDialog.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
			saveFileDialog.Filter = "文本文件(*.ws)|*.ws|所有文件(*.*)|*.*";
			if (saveFileDialog.ShowDialog(this) == DialogResult.OK)
			{
				string FileName = saveFileDialog.FileName;
				XmlDocument doc = new XmlDocument();
				doc.AppendChild(doc.CreateXmlDeclaration("1.0", "GB2312", null));
				XmlElement root = doc.CreateElement("WorkSpaces");
				foreach (FormWorkSpace f in MdiChildren)
				{
					XmlElement eWork = doc.CreateElement("WorkSpace");
					//Form属性
					eWork.SetAttribute("DockState", f.DockState.ToString());
					//ws属性
					eWork.SetAttribute("Name", f.ws.Name);
					eWork.SetAttribute("StartTime", f.ws.StartTime.ToString());
					eWork.SetAttribute("StopTime", f.ws.StopTime.ToString());
					eWork.SetAttribute("ReceiveTickEnable", f.ws.ReceiveTickEnable.ToString());
					//api
					XmlElement eApis = doc.CreateElement("Apis");
					foreach (var api in f.ws.Api.Apis)
					{
						XmlElement eApi = doc.CreateElement("api");
						eApis.Value = api.ToString();
						eApis.AppendChild(eApi);
					}
					eWork.AppendChild(eApis);
					//所有数据K线相关
					XmlElement eDatas = doc.CreateElement("Datas");
					foreach (var v in f.ws.Datas)
					{
						XmlElement data = doc.CreateElement("Data");
						data.SetAttribute("Instrument", v.Instrument);
						data.SetAttribute("InstrumentOrder", v.InstrumentOrder);
						data.SetAttribute("Interval", v.Interval.ToString());
						data.SetAttribute("IntervalType", v.IntervalType.ToString());
						eDatas.AppendChild(data);
					}
					eWork.AppendChild(eDatas);
					//策略相关
					XmlElement eStrategys = doc.CreateElement("Strategies");
					foreach (var v in f.ws.Strategies)
					{
						XmlElement eStra = doc.CreateElement("Strategy");
						eStra.SetAttribute("Type", v.GetType().FullName);
						XmlElement eParams = doc.CreateElement("Params");
						foreach (var fi in v.GetType().GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static))
						{
							if (fi.GetCustomAttributes(typeof (ParameterAttribute), false).Any())
							{
								XmlElement param = doc.CreateElement("Parameter");
								param.SetAttribute(fi.Name, fi.GetValue(v).ToString());
								eParams.AppendChild(param);
							}
						}
						eStra.AppendChild(eParams);
						eStrategys.AppendChild(eStra);
					}
					eWork.AppendChild(eStrategys);
					root.AppendChild(eWork);
					//lines += string.Format("<Content ID={0} DockState={1} IsFloat={2}\r\n", i++, f.DockState, f.IsFloat);
				}
				//File.WriteAllText(FileName, lines);
				//this.dockPanel1.SaveAsXml(FileName);
				doc.AppendChild(root);
				doc.Save(FileName);
			}
		}

		private void ExitToolsStripMenuItem_Click(object sender, EventArgs e)
		{
			Close();
		}

		private void CutToolStripMenuItem_Click(object sender, EventArgs e)
		{
		}

		private void CopyToolStripMenuItem_Click(object sender, EventArgs e)
		{
		}

		private void PasteToolStripMenuItem_Click(object sender, EventArgs e)
		{
		}

		private void ToolBarToolStripMenuItem_Click(object sender, EventArgs e)
		{
			this.toolStrip.Visible = this.toolBarToolStripMenuItem.Checked;
		}

		private void StatusBarToolStripMenuItem_Click(object sender, EventArgs e)
		{
			this.statusStrip.Visible = this.statusBarToolStripMenuItem.Checked;
		}

		private void CascadeToolStripMenuItem_Click(object sender, EventArgs e)
		{
			LayoutMdi(MdiLayout.Cascade);
		}

		private void TileVerticalToolStripMenuItem_Click(object sender, EventArgs e)
		{
			LayoutMdi(MdiLayout.TileVertical);
		}

		private void TileHorizontalToolStripMenuItem_Click(object sender, EventArgs e)
		{
			LayoutMdi(MdiLayout.TileHorizontal);
		}

		private void ArrangeIconsToolStripMenuItem_Click(object sender, EventArgs e)
		{
			LayoutMdi(MdiLayout.ArrangeIcons);
		}

		private void CloseAllToolStripMenuItem_Click(object sender, EventArgs e)
		{
			foreach (var childForm in MdiChildren)
			{
				childForm.Close();
			}
		}

		private void MainForm_MdiChildActivate(object sender, EventArgs e)
		{
			if (ActiveMdiChild == null || ActiveMdiChild.GetType() != typeof(FormWorkSpace))
			{
				return;
			}
			this._fWs.propertyGridEx1.SelectedObject = (ActiveMdiChild as FormWorkSpace).ws;
			this._fWs.propertyGridEx1.Text = (ActiveMdiChild as FormWorkSpace).Text;
		}
	}
}
